<template>
    <div class="page-container">
        <div class="header">
            <h1>视频管理 {{ currentStoreName ? `- ${currentStoreName}` : '' }}</h1>
            <div class="header-actions">
                <div class="search-container">
                    <input type="text" v-model="searchQuery" placeholder="搜索视频标题或描述...">
                </div>
                <button class="btn" @click="openUploadModal">上传视频</button>
            </div>
        </div>

        <div v-if="loading" class="loading-state">正在加载视频...</div>
        <div v-if="error" class="error-state">{{ error }}</div>

        <div v-if="videos" class="video-grid">
            <div class="video-card" v-for="video in filteredVideos" :key="video.videoId">
                <div class="video-thumbnail">
                    <img :src="video.coverImage" alt="Video thumbnail">
                    <div class="play-icon"><svg viewBox="0 0 24 24"><path d="M8 5v14l11-7z"></path></svg></div>
                </div>
                <div class="video-info">
                    <h3 class="video-title">{{ video.title }}</h3>
                    <p class="video-description">{{ video.description }}</p>
                    <div class="video-meta">
                        <span>观看: {{ formatCount(video.views) }}</span>
                        <span>点赞: {{ formatCount(video.likes) }}</span>
                    </div>
                </div>
                <div class="video-actions">
                    <a href="#" class="action-btn" @click.prevent="editVideo(video)">编辑</a>
                    <a href="#" class="action-btn delete" @click.prevent="deleteVideo(video.videoId)">删除</a>
                </div>
            </div>
        </div>
        
        <!-- Edit Video Modal -->
        <transition name="modal-fade">
            <div v-if="isEditModalVisible" class="modal-overlay" @click.self="closeEditModal">
                <div class="modal-content">
                    <button class="close-modal-btn" @click="closeEditModal">&times;</button>
                    <h2>编辑视频</h2>
                    <form v-if="editingVideo" @submit.prevent="saveVideo">
                        <div class="form-group">
                            <label for="video-title">标题</label>
                            <input type="text" id="video-title" v-model="editingVideo.title" required>
                        </div>
                        <div class="form-group">
                            <label for="video-description">描述</label>
                            <textarea id="video-description" v-model="editingVideo.description" rows="4"></textarea>
                        </div>
                        <div class="form-group">
                            <label>封面图片</label>
                            <div class="cover-image-upload">
                                <input type="file" id="video-cover-input" @change="handleCoverImageUpload" accept="image/*" class="file-input-hidden">
                                <label for="video-cover-input" class="file-input-label">
                                    <span v-if="!editingVideo.coverImage">选择图片</span>
                                    <span v-else>更换图片</span>
                                </label>
                                <div v-if="editingVideo.coverImage" class="image-preview">
                                    <img :src="editingVideo.coverImage" alt="Cover image preview">
                                </div>
                                <div v-else>
                                    <img :src="defaultThumbnail" alt="Cover image preview">
                                </div>
                            </div>
                        </div>
                        <div class="form-group">
                            <label>关联商品</label>
                            <div class="product-search-bar">
                                <input type="text" v-model="productSearchQuery" placeholder="搜索商品..." class="product-search-input">
                            </div>
                            <div v-if="loadingProductsAndTags" class="loading-small">正在加载商品...</div>
                            <div v-else-if="editingVideo && editingVideo.productIds" class="selection-box product-selection">
                                <div v-for="product in filteredAllProducts" :key="product.productId" class="product-item">
                                    <input type="checkbox"
                                           :id="'edit-prod-' + product.productId"
                                           :value="product.productId"
                                           v-model="editingVideo.productIds"
                                           class="product-checkbox">
                                    <label :for="'edit-prod-' + product.productId" class="product-label">
                                        <img :src="product.mainImage || defaultThumbnail" :alt="product.name" class="product-image">
                                        <div class="product-details">
                                            <span class="product-name" :title="product.name">{{ product.name }}</span>
                                            <span class="product-price">¥{{ product.price }}</span>
                                            <span class="product-store">商店: {{ product.storeId }}</span>
                                        </div>
                                    </label>
                                </div>
                            </div>
                        </div>
                        <div class="modal-actions">
                            <button type="submit" class="btn">保存更改</button>
                            <button type="button" class="btn btn-secondary" @click="closeEditModal">取消</button>
                        </div>
                    </form>
                </div>
            </div>
        </transition>

        <!-- Upload Video Modal -->
        <transition name="modal-fade">
            <div v-if="isUploadModalVisible" class="modal-overlay" @click.self="closeUploadModal">
                <div class="modal-content upload-modal-content">
                    <div class="modal-header-custom">
                        <h2>上传新视频</h2>
                        <button class="close-modal-btn" @click="closeUploadModal">&times;</button>
                    </div>
                    <form @submit.prevent="createNewVideo" class="upload-form">
                        <div class="upload-form-body">
                            <div class="upload-form-left">
                                <div class="form-group">
                                    <label for="new-video-title">标题</label>
                                    <input type="text" id="new-video-title" v-model="newVideo.title" required>
                                </div>
                                <div class="form-group">
                                    <label for="new-video-description">描述</label>
                                    <textarea id="new-video-description" v-model="newVideo.description" rows="4"></textarea>
                                </div>
                                <div class="form-row">
                                    <div class="form-group upload-box-wrapper">
                                        <label>封面图片 (必须)</label>
                                        <input type="file" id="new-video-cover-input" @change="handleNewCoverImageUpload" accept="image/*" class="file-input-hidden" required>
                                        <label for="new-video-cover-input" class="file-input-label-v2">
                                            <img v-if="newVideo.coverImage" :src="newVideo.coverImage" alt="New cover preview" class="upload-preview-v2">
                                            <div v-else class="upload-placeholder-v2">
                                                <svg viewBox="0 0 24 24" width="32" height="32"><path d="M21.09,5.51A1,1,0,0,0,20,5H4A1,1,0,0,0,3,6V18a1,1,0,0,0,1,1H20a1,1,0,0,0,1-1V6A1,1,0,0,0,21.09,5.51ZM5,17V7H19V17Z"/><path d="M10.5,13.5a2.5,2.5,0,1,0-2.5-2.5A2.5,2.5,0,0,0,10.5,13.5Z"/><path d="M19,12.2a1,1,0,0,0-.57-.9,1,1,0,0,0-1.09.21L13,15.89,11.33,14a1,1,0,0,0-1.41,1.41l2.39,2.39a1,1,0,0,0,1.41,0L18.42,13.3A1,1,0,0,0,19,12.2Z"/></svg>
                                                <span>选择封面</span>
                                            </div>
                                        </label>
                                    </div>
                                    <div class="form-group upload-box-wrapper">
                                        <label>视频文件 (必须)</label>
                                        <input type="file" id="new-video-file-input" @change="handleVideoFileUpload" accept="video/*" class="file-input-hidden" required>
                                        <label for="new-video-file-input" class="file-input-label-v2">
                                            <div v-if="uploadingVideo" class="upload-placeholder-v2">
                                                <span>处理中...</span>
                                            </div>
                                            <div v-else-if="newVideo.videoUrl" class="upload-placeholder-v2 video-selected">
                                                <svg viewBox="0 0 24 24" width="32" height="32"><path d="M21.5,16V8a2,2,0,0,0-2-2H4.5a2,2,0,0,0-2,2v8a2,2,0,0,0,2,2h15A2,2,0,0,0,21.5,16ZM5.5,8H18.5a1,1,0,0,1,1,1v6a1,1,0,0,1-1,1H5.5a1,1,0,0,1-1-1V9A1,1,0,0,1,5.5,8Zm1,5.25L10,11.5v-1a.5.5,0,0,1,.85-.35l3,1.75a.5.5,0,0,1,0,.7l-3,1.75A.5.5,0,0,1,10,14v-1l-3.5,1.75Z"/></svg>
                                                <span class="video-file-name">{{ videoFileName || '视频已选择' }}</span>
                                                <small v-if="newVideo.duration > 0">时长: {{ newVideo.duration }}s</small>
                                            </div>
                                            <div v-else class="upload-placeholder-v2">
                                                <svg viewBox="0 0 24 24" width="32" height="32"><path d="M21.5,16V8a2,2,0,0,0-2-2H4.5a2,2,0,0,0-2,2v8a2,2,0,0,0,2,2h15A2,2,0,0,0,21.5,16ZM5.5,8H18.5a1,1,0,0,1,1,1v6a1,1,0,0,1-1,1H5.5a1,1,0,0,1-1-1V9A1,1,0,0,1,5.5,8Zm1,5.25L10,11.5v-1a.5.5,0,0,1,.85-.35l3,1.75a.5.5,0,0,1,0,.7l-3,1.75A.5.5,0,0,1,10,14v-1l-3.5,1.75Z"/></svg>
                                                <span>选择视频</span>
                                            </div>
                                        </label>
                                    </div>
                                </div>
                            </div>
                            <div class="upload-form-right">
                                <div class="form-group form-group-flex">
                                    <label>关联商品</label>
                                    <div class="product-search-bar">
                                        <input type="text" v-model="productSearchQuery" placeholder="搜索商品..." class="product-search-input">
                                    </div>
                                    <div v-if="loadingProductsAndTags" class="loading-small">正在加载商品...</div>
                                    <div v-else class="selection-box product-selection">
                                        <div v-for="product in filteredAllProducts" :key="product.productId" class="product-item">
                                            <input type="checkbox" :id="'prod-' + product.productId" :value="product.productId" v-model="newVideo.productIds" class="product-checkbox">
                                            <label :for="'prod-' + product.productId" class="product-label">
                                                <img :src="product.mainImage || defaultThumbnail" :alt="product.name" class="product-image">
                                                <div class="product-details">
                                                    <span class="product-name" :title="product.name">{{ product.name }}</span>
                                                    <span class="product-price">¥{{ product.price }}</span>
                                                    <span class="product-store">商店: {{ product.storeId }}</span>
                                                </div>
                                            </label>
                                        </div>
                                    </div>
                                </div>
                                <div class="form-group form-group-flex">
                                    <label>视频标签</label>
                                    <div v-if="loadingProductsAndTags" class="loading-small">正在加载标签...</div>
                                    <div v-else class="selection-box tags-selection">
                                        <div v-for="tag in allTags" :key="tag.tagId" class="checkbox-item tag-item">
                                            <input type="checkbox" :id="'tag-' + tag.tagId" :value="tag.tagId" v-model="newVideo.tagIds">
                                            <label :for="'tag-' + tag.tagId">{{ tag.name }}</label>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="upload-form-footer">
                            <div class="form-group-checkbox">
                                <input type="checkbox" id="new-video-private" v-model="newVideo.isPrivate">
                                <label for="new-video-private">设为私密视频</label>
                            </div>
                            <div class="modal-actions">
                                <button type="button" class="btn btn-secondary" @click="closeUploadModal">取消</button>
                                <button type="submit" class="btn" :disabled="uploadingVideo">
                                    {{ uploadingVideo ? '正在上传...' : '确认上传' }}
                                </button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </transition>
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch, computed } from 'vue';
import { useRoute } from 'vue-router';
import { api } from '@/network/api';

interface Video {
    videoId: number;
    title: string;
    description: string;
    coverImage: string;
    views: number;
    likes: number;
    productIds?: number[];
    storeId?: number;
}

interface Product {
    productId: number;
    name: string;
    mainImage: string;
    price: number;
    storeId: number;
}

interface Tag {
    tagId: number;
    name: string;
}

interface Store {
    storeId: number;
    name: string;
}

interface VideoDTO {
    video: string; // Base64 编码的视频字符串
    cover_image: string; // Base64 编码的封面图片字符串
    title: string;
    description: string;
    tags: number[]; // 标签ID列表
    is_private: boolean;
    products: number[]; // 关联商品ID列表
    duration: number;
}

const route = useRoute();
const videos = ref<Video[]>([]);
const loading = ref(true);
const error = ref<string | null>(null);
const currentStoreId = ref<number | null>(null);
const currentStoreName = ref<string | null>(null);
const isAdmin = ref(true);
const isEditModalVisible = ref(false);
const editingVideo = ref<Video | null>(null);
const store = ref<any>(null);
const isUploadModalVisible = ref(false);
const loadingProductsAndTags = ref(false);
const uploadingVideo = ref(false);
const videoFileName = ref('');
const allProducts = ref<Product[]>([]);
const allTags = ref<Tag[]>([]);
const searchQuery = ref('');
const productSearchQuery = ref('');

const initialNewVideoState = {
    title: '',
    description: '',
    coverImage: '',
    videoUrl: '',
    duration: 0,
    productIds: [] as number[],
    tagIds: [] as number[],
    isPrivate: false,
};
const newVideo = ref({ ...initialNewVideoState });

const filteredVideos = computed(() => {
    if (!videos.value) return [];
    if (!searchQuery.value) {
        return videos.value;
    }
    const lowerCaseQuery = searchQuery.value.toLowerCase();
    return videos.value.filter(video =>
        video.title.toLowerCase().includes(lowerCaseQuery) ||
        (video.description && video.description.toLowerCase().includes(lowerCaseQuery))
    );
});

const filteredAllProducts = computed(() => {
    if (!allProducts.value) return [];
    if (!productSearchQuery.value) {
        return allProducts.value;
    }
    const lowerCaseQuery = productSearchQuery.value.toLowerCase();
    return allProducts.value.filter(product =>
        product.name.toLowerCase().includes(lowerCaseQuery)
    );
});

const defaultThumbnail = '/avatar/avatar.png';

const hardcodedTags = [
    { tagId: 2, name: '狗狗' },
    { tagId: 3, name: '猫咪' },
    { tagId: 4, name: '水族' },
    { tagId: 5, name: '护理' },
    { tagId: 6, name: '训练' },
    { tagId: 7, name: '宠物食品' },
    { tagId: 8, name: '用品测试' },
];

const fetchVideos = async () => {
    try {
        loading.value = true;
        let response;

        if (currentStoreId.value) {
            response = await api.getVideosStore(currentStoreId.value);
        } else {
            response = await api.getVideosByMemberLevel(); 
        }

        if (response && response.data && Array.isArray(response.data.data)) {
            videos.value = response.data.data;
        } else if (response && response.data && Array.isArray(response.data)) {
            videos.value = response.data;
        }
         else {
            videos.value = [];
        }
        error.value = null;
    } catch (err) {
        console.error("获取视频列表失败:", err);
        error.value = '视频列表加载失败，请稍后重试。';
    } finally {
        loading.value = false;
    }
};

const getStoreInfo = async (storeId: number) => {
    try {
        const response = await api.getStoreDetail(storeId);
        if (response.data && response.data.data) {
            currentStoreName.value = response.data.data.name;
        }
    } catch (err) {
        console.error("获取商店信息失败:", err);
        currentStoreName.value = `商店 ${storeId}`;
    }
};

// 监听路由变化
watch(() => route.params.storeId, async (newStoreId) => {
    if (newStoreId) {
        currentStoreId.value = parseInt(newStoreId as string);
        await getStoreInfo(currentStoreId.value);
    } else {
        currentStoreId.value = null;
        currentStoreName.value = null;
    }
    await fetchVideos();
}, { immediate: true });

const formatCount = (num: number) => {
    if (num > 9999) {
        return (num / 10000).toFixed(1) + 'w';
    }
    if (num > 999) {
        return (num / 1000).toFixed(1) + 'k';
    }
    return num;
};

const editVideo = async (video: Video) => {
    productSearchQuery.value = '';
    loadingProductsAndTags.value = true;
    isEditModalVisible.value = true;
    try {
        const [productsResponse, videoProductsResponse] = await Promise.all([
            api.getProductsList(),
            api.getProductsByVideoId(video.videoId)
        ]);

        allProducts.value = productsResponse.data.data;
        const currentProductIds = videoProductsResponse.data.data.map((p: Product) => p.productId);

        editingVideo.value = {
            ...video,
            productIds: currentProductIds
        };
    } catch (err) {
        console.error("加载编辑数据失败:", err);
        alert("加载编辑数据失败，请稍后重试。");
        closeEditModal();
    } finally {
        loadingProductsAndTags.value = false;
    }
};

const saveVideo = async () => {
    if (!editingVideo.value) return;
    try {
        // 第一步: 调用新接口，更新视频关联的商品
        if (editingVideo.value.videoId && editingVideo.value.productIds) {
            await api.updateVideoProducts({
                videoId: editingVideo.value.videoId,
                productIds: editingVideo.value.productIds,
            });
        }

        // 第二步: 调用原有接口，更新视频的基本信息
        await api.updateVideo(editingVideo.value);

        // 第三步: 刷新列表、关闭弹窗并提示用户
        await fetchVideos();
        closeEditModal();
        alert('视频信息已更新！');
    } catch (err: any) {
        console.error("更新视频失败:", err);
        alert('更新失败，请稍后重试。');
    }
};

const closeEditModal = () => {
    isEditModalVisible.value = false;
    editingVideo.value = null;
};

const handleCoverImageUpload = (event: Event) => {
    if (!editingVideo.value) return;
    const target = event.target as HTMLInputElement;
    if (target.files && target.files[0]) {
        const file = target.files[0];
        const reader = new FileReader();
        reader.onload = (e) => {
            if (editingVideo.value && e.target && typeof e.target.result === 'string') {
                editingVideo.value.coverImage = e.target.result;
            }
        };
        reader.readAsDataURL(file);
    }
};

const deleteVideo = (id: number) => {
    if (confirm(`确定要删除视频 ID: ${id} 吗?`)) {
        api.deleteVideo(id).then(() => {
            fetchVideos();
            alert(`视频 ID: ${id} 已删除`);
        }).catch((err: Error) => {
            console.error("删除视频失败:", err);
            alert('删除失败，请稍后重试。');
        });
    }
};

const openUploadModal = () => {
    newVideo.value = { ...initialNewVideoState, productIds: [], tagIds: [] };
    videoFileName.value = '';
    productSearchQuery.value = '';
    isUploadModalVisible.value = true;
    fetchProductsAndTags();
};

const closeUploadModal = () => {
    isUploadModalVisible.value = false;
};

const fetchProductsAndTags = async () => {
    loadingProductsAndTags.value = true;
    try {
        const productsResponse = await api.getProductsList();
        allProducts.value = productsResponse.data.data;

        allTags.value = hardcodedTags;
    } catch (err) {
        console.error("加载商品和标签失败:", err);
        alert("加载关联数据失败，请稍后重试。");
    } finally {
        loadingProductsAndTags.value = false;
    }
};

const handleNewCoverImageUpload = (event: Event) => {
    const target = event.target as HTMLInputElement;
    if (target.files && target.files[0]) {
        const file = target.files[0];
        const reader = new FileReader();
        reader.onload = (e) => {
            if (e.target && typeof e.target.result === 'string') {
                newVideo.value.coverImage = e.target.result;
            }
        };
        reader.readAsDataURL(file);
    }
};

const handleVideoFileUpload = (event: Event) => {
    const target = event.target as HTMLInputElement;
    if (target.files && target.files[0]) {
        const file = target.files[0];
        videoFileName.value = file.name;
        uploadingVideo.value = true;

        const reader = new FileReader();
        reader.onload = (e) => {
            if (e.target && typeof e.target.result === 'string') {
                newVideo.value.videoUrl = e.target.result;

                const videoElement = document.createElement('video');
                videoElement.onloadedmetadata = () => {
                    newVideo.value.duration = Math.round(videoElement.duration);
                    uploadingVideo.value = false;
                };
                videoElement.src = e.target.result;
            }
        };
        reader.readAsDataURL(file);
    }
};

const createNewVideo = async () => {
    if (!newVideo.value.title || !newVideo.value.videoUrl || !newVideo.value.coverImage) {
        alert("请填写所有必填项并上传文件。");
        return;
    }

    const videoData: VideoDTO = {
        title: newVideo.value.title,
        description: newVideo.value.description,
        video: newVideo.value.videoUrl,
        cover_image: newVideo.value.coverImage,
        duration: newVideo.value.duration,
        products: newVideo.value.productIds,
        tags: newVideo.value.tagIds,
        is_private: newVideo.value.isPrivate,
    };

    try {
        await api.uploadVideo(videoData);
        await fetchVideos();
        closeUploadModal();
        alert('新视频已成功上传！');
    } catch (err: any) {
        console.error("创建视频失败:", err);
        alert('上传失败，请稍后重试。');
    }
};

const fetchStore = async () => {
    try {
        const response = await api.getStoresNoId();
        const storeData = response.data;

        if (Array.isArray(storeData) && storeData.length > 0) {
            store.value = storeData[0];
        } else if (storeData && typeof storeData === 'object' && !Array.isArray(storeData)) {
            store.value = storeData;
        } else {
            store.value = null;
            console.error("未能获取到有效的店铺信息。");
        }
    } catch (error) {
        console.error("获取店铺信息失败:", error);
        throw error;
    }
};

onMounted(async () => {
    // fetchVideos(); // 由 watch 的 immediate: true 触发
    if (isAdmin.value) {
        fetchProductsAndTags();
    }
});
</script>

<style scoped>
.page-container {
    padding: 30px;
}
.header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
}
.header h1 {
    font-size: 2em;
    margin: 0;
}
.header-actions {
    display: flex;
    align-items: center;
    gap: 20px;
}
.search-container input {
    width: 300px;
    padding: 10px 15px;
    font-size: 1em;
    border-radius: 6px;
    border: 1px solid #ddd;
    transition: box-shadow 0.2s, border-color 0.2s;
}
.search-container input:focus {
    outline: none;
    border-color: #3498db;
    box-shadow: 0 0 0 3px rgba(52, 152, 219, 0.2);
}
.btn {
    background-color: #3498db;
    color: white;
    padding: 12px 20px;
    border: none;
    border-radius: 6px;
    cursor: pointer;
    text-decoration: none;
    font-size: 1em;
    font-weight: 500;
    transition: background-color 0.3s, transform 0.2s;
}
.btn:hover {
    background-color: #2980b9;
    transform: translateY(-2px);
}
.btn:disabled {
    background-color: #bdc3c7;
    cursor: not-allowed;
    transform: none;
}
.video-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
    gap: 25px;
}
.video-card {
    background-color: #fff;
    border-radius: 8px;
    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
    overflow: hidden;
    transition: transform 0.3s, box-shadow 0.3s;
    display: flex;
    flex-direction: column;
}
.video-card:hover {
    transform: translateY(-5px);
    box-shadow: 0 8px 12px rgba(0, 0, 0, 0.08);
}
.video-thumbnail {
    width: 100%;
    padding-top: 56.25%; /* 16:9 Aspect Ratio */
    position: relative;
}
.video-thumbnail img {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    object-fit: cover;
}
.play-icon {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    width: 50px;
    height: 50px;
    background-color: rgba(0, 0, 0, 0.5);
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
}
.play-icon svg {
    width: 24px;
    height: 24px;
    fill: #fff;
}
.video-info {
    padding: 15px;
    flex-grow: 1;
    display: flex;
    flex-direction: column;
}
.video-title {
    font-size: 1.2em;
    font-weight: 600;
    margin: 0 0 10px 0;
    line-height: 1.4;
    flex-grow: 1;
    text-align: left;
}
.video-description {
    font-size: 0.9em;
    color: #666;
    margin: 0 0 10px 0;
    line-height: 1.5;
    text-align: left;
}
.video-meta {
    color: #777;
    margin-top: 10px;
    display: flex;
    justify-content: space-between;
}
.video-actions {
    padding: 0 15px 15px;
    text-align: right;
}
.action-btn {
    color: #3498db;
    text-decoration: none;
    margin-left: 15px;
    font-weight: 500;
    font-size: 1.2em;
}
.action-btn:hover {
    text-decoration: underline;
}
.action-btn.delete {
    color: #e74c3c;
}
.loading-state, .error-state {
    padding: 20px;
    text-align: center;
    font-size: 1.2em;
    color: #666;
}

/* Modal Styles */
.modal-fade-enter-active, .modal-fade-leave-active {
    transition: opacity 0.3s ease;
}
.modal-fade-enter-from, .modal-fade-leave-to {
    opacity: 0;
}
.modal-fade-enter-active .modal-content,
.modal-fade-leave-active .modal-content {
    transition: transform 0.3s ease;
}
.modal-fade-enter-from .modal-content,
.modal-fade-leave-to .modal-content {
    transform: scale(0.95);
}

.modal-overlay {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 1000;
    overflow-y: auto;
    padding: 20px 0;
}

.modal-content {
    background-color: #fff;
    padding: 30px 40px;
    border-radius: 12px;
    box-shadow: 0 10px 25px rgba(0,0,0,0.1);
    width: 90%;
    max-width: 900px;
    position: relative;
    transform: scale(1);
    margin: auto;
}

.upload-modal-content {
    max-width: 1100px; /* Wider modal */
}

.modal-header-custom {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-bottom: 20px;
    border-bottom: 1px solid #e5e7eb;
    margin-bottom: 25px;
}

.modal-header-custom h2 {
    margin: 0;
    font-size: 1.5em;
    font-weight: 600;
}

.upload-form {
    display: flex;
    flex-direction: column;
}

.upload-form-body {
    display: flex;
    gap: 30px;
}

.upload-form-left {
    flex: 1.2;
}

.upload-form-right {
    flex: 1;
    display: flex;
    flex-direction: column;
    gap: 20px;
}

.upload-form-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 30px;
    padding-top: 20px;
    border-top: 1px solid #e5e7eb;
}

.upload-box-wrapper {
    flex: 1;
}

.file-input-label-v2 {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    text-align: center;
    padding: 10px;
    background-color: #f9fafb;
    border: 2px dashed #d1d5db;
    border-radius: 8px;
    cursor: pointer;
    transition: all 0.3s;
    font-weight: 500;
    height: 160px;
    position: relative;
    overflow: hidden;
}

.file-input-label-v2:hover {
    background-color: #f3f4f6;
    border-color: #3498db;
}

.upload-placeholder-v2 {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    gap: 8px;
    color: #6b7280;
}

.upload-placeholder-v2 svg {
    color: #9ca3af;
}

.upload-preview-v2 {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.video-selected {
    color: #16a34a;
}
.video-selected svg {
    color: #16a34a;
}
.video-file-name {
    font-size: 0.9em;
    font-weight: 600;
    word-break: break-all;
    padding: 0 5px;
}

.form-group-flex {
    display: flex;
    flex-direction: column;
    height: 100%;
}

.tags-selection {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
    padding: 5px;
}

.tag-item {
    background-color: #f3f4f6;
    border-radius: 16px;
    transition: all 0.2s;
}
.tag-item:hover {
    background-color: #e5e7eb;
}
.tag-item input[type="checkbox"] {
    display: none;
}
.tag-item label {
    padding: 6px 14px;
    cursor: pointer;
    display: block;
    margin: 0;
    font-weight: 500;
    font-size: 0.9em;
}
.tag-item input[type="checkbox"]:checked + label {
    background-color: #3498db;
    color: white;
    border-radius: 16px;
}

.close-modal-btn {
    position: absolute;
    top: 15px;
    right: 15px;
    background: transparent;
    border: none;
    font-size: 28px;
    line-height: 1;
    color: #aaa;
    cursor: pointer;
    transition: color 0.3s;
}

.close-modal-btn:hover {
    color: #333;
}

.modal-content h2 {
    margin-top: 0;
    margin-bottom: 30px;
    font-size: 1.6em;
    font-weight: 600;
    color: #333;
    text-align: center;
}

.form-group {
    margin-bottom: 22px;
}

.form-group label {
    display: block;
    margin-bottom: 8px;
    font-weight: 600;
    font-size: 0.9em;
    color: #444;
}

.form-group input[type="text"],
.form-group textarea {
    width: 100%;
    padding: 12px;
    border: 1px solid #ddd;
    border-radius: 6px;
    font-size: 1em;
    box-sizing: border-box;
    transition: border-color 0.3s, box-shadow 0.3s;
}

.form-group input[type="text"]:focus,
.form-group textarea:focus {
    outline: none;
    border-color: #3498db;
    box-shadow: 0 0 0 3px rgba(52, 152, 219, 0.2);
}

.form-group textarea {
    resize: vertical;
    min-height: 80px;
}

.form-row {
    display: flex;
    gap: 20px;
}
.form-row .form-group {
    flex: 1;
}

/* Custom file upload */
.cover-image-upload {
    display: flex;
    align-items: center;
    gap: 20px;
}

.file-input-hidden {
    display: none;
}

.file-input-label {
    display: flex;
    justify-content: center;
    align-items: center;
    text-align: center;
    padding: 10px;
    background-color: #f7f9fc;
    color: #555;
    border: 2px dashed #dce4f0;
    border-radius: 8px;
    cursor: pointer;
    transition: all 0.3s;
    font-weight: 500;
    height: 150px;
    position: relative;
}

.file-input-label.wide {
    width: 100%;
}

.file-input-label:hover {
    background-color: #eff3f8;
    border-color: #3498db;
}

.upload-placeholder {
    display: flex;
    flex-direction: column;
    gap: 5px;
    color: #888;
}

.upload-preview {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    object-fit: cover;
    border-radius: 6px;
}

.image-preview {
    margin-top: 0;
    width: 120px;
    height: 120px;
    border-radius: 8px;
    overflow: hidden;
    border: 1px solid #ddd;
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: #f9f9f9;
}

.image-preview img {
    width: 100%;
    height: 100%;
    object-fit: cover;
    border: none;
    max-height: none;
}

.modal-actions {
    display: flex;
    justify-content: flex-end;
    gap: 15px;
    margin-top: 0;
}

.modal-actions .btn {
    margin-left: 0;
}

.btn-secondary {
    background-color: #bdc3c7;
    color: #333;
}

.btn-secondary:hover {
    background-color: #a2acb1;
}

/* Selection Box for Products/Tags */
.selection-box {
    max-height: 300px;
    overflow-y: auto;
    border: 1px solid #ddd;
    border-radius: 6px;
    padding: 15px;
    background-color: #fdfdfd;
    flex-grow: 1; /* allow it to fill space in flex container */
}

.product-selection {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
    gap: 15px;
}

.checkbox-item {
    display: flex;
    align-items: center;
    padding: 6px 0;
}
.checkbox-item input[type="checkbox"] {
    margin-right: 10px;
    width: 16px;
    height: 16px;
    cursor: pointer;
}
.checkbox-item label {
    margin-bottom: 0;
    font-weight: 500;
    cursor: pointer;
}
.loading-small {
    padding: 10px;
    color: #888;
}

/* Product Item Styles */
.product-item {
    position: relative;
    height: 100%;
}
.product-checkbox {
    position: absolute;
    top: 10px;
    left: 10px;
    width: 20px;
    height: 20px;
    z-index: 2;
    opacity: 0;
    cursor: pointer;
}
.product-label {
    display: flex;
    flex-direction: column;
    border: 1px solid #e0e0e0;
    border-radius: 8px;
    overflow: hidden;
    cursor: pointer;
    transition: all 0.2s ease-in-out;
    height: 100%;
    background-color: #fff;
}
.product-label:hover {
    transform: translateY(-3px);
    box-shadow: 0 4px 12px rgba(0,0,0,0.08);
}
.product-checkbox:checked + .product-label {
    border-color: #3498db;
    box-shadow: 0 0 0 3px rgba(52, 152, 219, 0.3);
}
.product-image {
    width: 100%;
    height: 120px;
    object-fit: cover;
    background-color: #f0f0f0;
}
.product-details {
    padding: 12px;
    flex-grow: 1;
    display: flex;
    flex-direction: column;
}
.product-name {
    font-weight: 600;
    color: #333;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    margin-bottom: 5px;
}
.product-price {
    color: #e74c3c;
    font-weight: 600;
    font-size: 1em;
    margin-top: auto;
}
.product-store {
    font-size: 0.8em;
    color: #888;
    margin-top: 5px;
}
.form-group-checkbox {
    display: flex;
    align-items: center;
    justify-content: flex-start; /* Aligned to left in the footer */
    margin: 0;
}
.form-group-checkbox input[type="checkbox"] {
    width: 16px;
    height: 16px;
    margin-right: 8px;
    cursor: pointer;
}
.form-group-checkbox label {
    margin-bottom: 0;
    font-weight: 500;
    cursor: pointer;
    color: #555;
}

.product-search-input {
    width: 100%;
    padding: 8px 12px;
    font-size: 0.9em;
    border-radius: 6px;
    border: 1px solid #ddd;
    box-sizing: border-box;
    margin-bottom: 10px;
}
</style> 